﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using System.IO;

namespace NCRGEA.Reports
{
    public partial class frmDynamicReport : Form
    {
        private DataTable _tbl;
        private MemoryStream m_rdl;
        public frmDynamicReport()
        {
            InitializeComponent();
        }

        public frmDynamicReport(DataTable tbl) : this()
        {
            _tbl = tbl;
        }

        private void frmDynamicReport_Load(object sender, EventArgs e)
        {
            CreateReport();
        }

        private void ShowReport()
        {
            this.reportViewer1.Reset();
            this.reportViewer1.LocalReport.LoadReportDefinition(m_rdl);
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("MyData", _tbl));
            this.reportViewer1.RefreshReport();
        }

        private void CreateReport()
        {
            try
            {
                List<string> allFields = GetAvailableFields();
                ReportOptionsDialog dlg = new ReportOptionsDialog(allFields);
                if (dlg.ShowDialog() != DialogResult.OK)
                    return;
               
                List<string> selectedFields = dlg.GetSelectedFields();

                if (m_rdl != null)
                    m_rdl.Dispose();
                m_rdl = GenerateRdl(allFields, selectedFields);

                ShowReport();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




        private List<string> GetAvailableFields()
        {
            DataTable dataTable = _tbl;
            List<string> availableFields = new List<string>();
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                availableFields.Add(dataTable.Columns[i].ColumnName);
            }
            return availableFields;
        }

        private MemoryStream GenerateRdl(List<string> allFields, List<string> selectedFields)
        {
            MemoryStream ms = new MemoryStream();
            RdlGenerator gen = new RdlGenerator();
            gen.AllFields = allFields;
            gen.SelectedFields = selectedFields;
            gen.WriteXml(ms);
            ms.Position = 0;
            return ms;
        }
    }
}
